<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑分类' : '新增分类'"
    width="500px"
    @close="handleClose"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="分类名称" prop="label">
        <el-input
          v-model="form.label"
          placeholder="请输入分类名称"
        />
      </el-form-item>
      
      <el-form-item label="分类代码" prop="code">
        <el-input
          v-model="form.code"
          placeholder="请输入分类代码"
          :disabled="isEdit"
        />
      </el-form-item>
      
      <el-form-item label="父级分类" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          :data="categoryOptions"
          placeholder="请选择父级分类"
          style="width: 100%"
          :props="{ label: 'label', value: 'id' }"
        />
      </el-form-item>
      
      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="form.sort"
          :min="0"
          :max="999"
          placeholder="排序"
        />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

interface CategoryForm {
  label: string
  code: string
  parentId: string
  sort: number
  description: string
}

interface Props {
  modelValue: boolean
  formData?: Partial<CategoryForm>
  isEdit?: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  formData: () => ({}),
  isEdit: false
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const loading = ref(false)

const form = reactive<CategoryForm>({
  label: '',
  code: '',
  parentId: '',
  sort: 0,
  description: ''
})

const rules: FormRules = {
  label: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分类名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类代码', trigger: 'blur' },
    { min: 2, max: 50, message: '分类代码长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 分类选项（用于选择父级分类）
const categoryOptions = ref([
  { id: 'work_type', label: '作业类型' },
  { id: 'risk_level', label: '风险等级' },
  { id: 'safety_measures', label: '安全措施库' },
  { id: 'personnel_type', label: '人员类型' }
])

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      Object.assign(form, {
        label: newData.label || '',
        code: newData.code || '',
        parentId: newData.parentId || '',
        sort: newData.sort || 0,
        description: newData.description || ''
      })
    }
  },
  { immediate: true, deep: true }
)

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const action = props.isEdit ? '更新' : '创建'
    ElMessage.success(`分类${action}成功`)
    
    emit('success')
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.el-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>

